/*
  学习目标：实现缓存效果
  步骤：
     1. 
     2. 
     3. 
*/
import React, { useEffect, useState } from 'react';
import Footer from './components/Footer';
import Header from './components/Header';
import Main from './components/Main';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  const [list, setList] = useState([]);

  // 💥💥
  // 容易踩坑点
  // 💥 依赖项先声明，后监听
  // 💥 多个useEffect，先写挂载逻辑， 后写更新逻辑

  // 1. 挂载后 从缓存中取出数据， 更新list
  useEffect(() => {
    const newList = JSON.parse(localStorage.getItem('tod-list-83')) || [];
    setList(newList);
  }, []);

  // 2. 监听list的变化
  useEffect(() => {
    localStorage.setItem('tod-list-83', JSON.stringify(list));
  }, [list]); // 挂载， 更新 二合一

  const handleDelById = (id) => {
    const newList = list.filter((item) => item.id !== id);
    setList(newList);
  };

  const handleUpdateById = (id) => {
    const newList = list.map((item) => {
      return {
        ...item,
        isDone: item.id === id ? !item.isDone : item.isDone,
      };
    });

    setList(newList);
  };

  const handleAdd = (task) => {
    const newItem = {
      id: Date.now(),
      task,
      isDone: false,
    };

    setList([newItem, ...list]);
  };

  const [type, setType] = useState('all');

  const handleUpdateType = (type) => {
    setType(type);
  };

  const showList = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });

  return (
    <section className="todoapp">
      <Header handleAdd={handleAdd} />
      <Main
        list={showList}
        handleDelById={handleDelById}
        handleUpdateById={handleUpdateById}
      />
      <Footer type={type} handleUpdateType={handleUpdateType} />
    </section>
  );
}
